package com.library.controller;

import com.library.bean.Admin;
import com.library.bean.ReaderCard;
import com.library.bean.ReaderInfo;
import com.library.service.LoginService;
import com.library.service.ReaderCardService;
import com.library.service.ReaderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


@Controller
@CrossOrigin
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private ReaderInfoService readerInfoService;

    @Autowired
    private ReaderCardService readerCardService;


    @RequestMapping(value = {"/","/login.html","/login"})
    public String toLogin(HttpServletRequest request){
        //清除session作用域里的信息
        request.getSession().invalidate();
        return "index";

    }


    //登录验证
    @RequestMapping(value = "/loginCheck",method = RequestMethod.POST)
    public @ResponseBody Object loginCheck(HttpServletRequest request){
        String username=request.getParameter("username");
        String passwd=request.getParameter("passwd");

        //判断是读者还是管理员
        boolean isReader=loginService.hasMatchReader(username,passwd);
        boolean isAdmin=loginService.hasMatchAdmin(username,passwd);

        HashMap<String,String> res=new HashMap<>();
        //如果是管理员
        if (isAdmin){
            Admin admin =new Admin();
            admin.setUsername(username);
            admin.setPassword(passwd);
            //获取管理员id
            Long id=loginService.getAdminId(username);
            admin.setAdminId(id);
            request.getSession().setAttribute("admin",admin);
            res.put("stateCode","1");
            res.put("msg","管理员登陆成功");

        }else if(isReader){
            ReaderCard readerCard=loginService.findReaderCardByReaderId(username);
            request.getSession().setAttribute("readercard",readerCard);
            res.put("stateCode","2");
            res.put("msg","读者登陆成功");

        }else{
            res.put("stateCode","0");
            res.put("msg","用户名或密码错误");
        }
        return res;

    }

    @RequestMapping({"register","/register.html"})
    public ModelAndView register(){
        return new ModelAndView("register");

    }


    //添加读者信息并返回登录页
    @RequestMapping("reader_add")
    public ModelAndView readerAdd(String name, String password, String ruserPassword, String sex, String birth, String address, String phone, RedirectAttributes attributes){
        ReaderInfo readerInfo=getReaderInfo(0L,name,sex,birth,address,phone);
        //添加数据到数据库，并得到返回的id
        long readerId=readerInfoService.ReaderInfo(readerInfo);

        readerInfo.setReader_id(readerId);
        if (readerId>0&&readerCardService.addReaderCard(readerInfo,password)){
            attributes.addFlashAttribute("succ","添加读者信息成功");

        }else attributes.addFlashAttribute("fail","添加读者信息失败");

        return new ModelAndView("index");

    }

    //读者信息封装
    private ReaderInfo getReaderInfo(long readerId, String name, String sex, String birth, String address, String phone) {
        ReaderInfo readerInfo=new ReaderInfo();
        //转换为date格式
        Date date=new Date();

        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            date=sdf.parse(birth);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        readerInfo.setAddress(address);
        readerInfo.setBirth(birth);
        readerInfo.setName(name);
        readerInfo.setPhone(phone);
        readerInfo.setReader_id(readerId);
        readerInfo.setSex(sex);
        return readerInfo;




    }

    @RequestMapping("/logout.html")
    public String logout(HttpServletRequest request){
        //session信息无效化
        request.getSession().invalidate();
        return "redirect:/login.html";

    }

    //密码修改
    @RequestMapping("/admin_repasswd.html")
    public ModelAndView reAdminPasswd(){
        return new ModelAndView("admin_repasswd");
    }

    @RequestMapping("/admin_repasswd_do")
    public String reAdminPasswdDo(HttpServletRequest request,String oldPasswd,String newPasswd,RedirectAttributes attributes){
        Admin admin= (Admin) request.getSession().getAttribute("admin");
        long id=admin.getAdminId();
        String password=loginService.getAdminPassword(id);
        if (password.equals(oldPasswd)){
            if (loginService.adminRePassword(id,newPasswd)){
                attributes.addFlashAttribute("succ","密码修改成功");
                return "redirect:/admin_repasswd.html";
            }else {
                attributes.addFlashAttribute("error","密码修改失败");
                return "redirect:/admin_repasswd.html";
            }
        }else{
            attributes.addFlashAttribute("error","密码错误");
            return "redirect:/admin_repasswd.html";
        }
    }


    @RequestMapping("/reader_repasswd.html")
    public ModelAndView reReaderPasswd(){
        return new ModelAndView("reader_repasswd");
    }

    @RequestMapping("/reader_repasswd_do")
    public String reReaderPasswdDo(HttpServletRequest request,String oldPasswd,String newPasswd,RedirectAttributes attributes){
        ReaderCard readerCard= (ReaderCard) request.getSession().getAttribute("readercard");
        long id=readerCard.getReader_id();
        String password=loginService.getReaderPassword(id);
        if (password.equals(oldPasswd)){
            if (loginService.readerRePassword(id,newPasswd)){
                attributes.addFlashAttribute("succ","密码修改成功");
                return "redirect:/reader_repasswd.html";
            }else {
                attributes.addFlashAttribute("error","密码修改失败");
                return "redirect:/reader_repasswd.html";
            }
        }else{
            attributes.addFlashAttribute("error","密码错误");
            return "redirect:/reader_repasswd.html";
        }
    }

}
